from scapy.all import *
import time,socket,select
con_iface= 'enp3s15'
con_iface= 'eth0'
con_iface= 'wlp3s0'
sock = conf.L2socket(iface=con_iface)
msg = b'a'*1000
port = 8899
import random
import queue
q = queue.Queue()
dip = '154.221.19.38'
so = socket.socket()
so.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

so.bind(('127.0.0.1', 0))

add = ('127.0.0.1',int(so.getsockname()[1]))

so.listen(1)

connso = None
sport=random.randint(40000,55000)
def aa(p):
    if q.qsize()>50:
        return
    connso.sendall(b'a')
    q.put(p)
    
def b():
    global connso
    connso = socket.socket()
    connso.connect(add)
    print ('sock ok')    
    a = sniff(prn=aa, filter="tcp and host %s and src port %s and dst port %s"%(dip,port,sport) ,store=0,iface=con_iface)
import threading


t = threading.Thread(target=b)
t.setDaemon(True)
t.start()
a,b=so.accept()
time.sleep(1)
ip = IP(dst=dip)
icmp = Ether()/ip/ICMP(type='echo-request')/(b'a'*555)
#while True:
    #time.sleep(1)
    #for i in range(100):
        #sock.send(icmp)  
    


tcp2 = Ether()/ip/TCP(sport=sport,dport=port,seq=random.randint(424324,43253455),ack=0,flags='S',window=60000)
sock.send(tcp2)  
tcp = None
maxAck = 0
notSeqMap = {}
co = 0
while True:
    r = select.select([a],[],[],0.3)
    if not r[0]:        
        print ('timeout')
        if tcp:
            sock.send(tcp)
        else:
            sock.send(tcp2)
        continue
    if a in r[0]:
        ss = a.recv(1000)
        for i in range(len(ss)):
            p = q.get()
            #p.show()
            t = p[TCP]
            i = p[IP]
            ip = IP(dst=i.src)
            d = t.payload.original
            if 'S' in t.flags:    
                tcp = Ether()/ip/TCP(sport=t.dport,dport=t.sport,seq=t.ack,ack=t.seq+1,flags='PA',window=60000)/msg
                sock.send(tcp)
                continue
            if 'F' in t.flags or 'R' in t.flags:
                print ('reset')
                continue
            
            if d[:16]!=b'a'*16:
                print ('error')
                continue
            co += 1
            print (co)            
            if maxAck <t.seq+len(d):
                            
                maxAck = t.seq+len(d)
                tcp = Ether()/ip/TCP(sport=t.dport,dport=t.sport,seq=t.ack,ack=maxAck,flags='PA',window=60000)/msg
                sock.send(tcp)

